﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security;
using SAIM.Models;
using SAIM.Models.BLL;
using Hangfire;
using Hangfire.SqlServer;

namespace SAIM.Controllers
{
    public class AccountController : Controller
    {
        private SAIMIdentity UserIdentity
        {
            get { return new SAIMIdentity(User.Identity); }
        }

        public void SignIn()
        {
            string callbackUrl = Url.Action("SignInCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);

            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = callbackUrl }, 
                    WsFederationAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);

            HttpContext.GetOwinContext().Authentication.SignOut(
                new AuthenticationProperties { RedirectUri = callbackUrl },
                WsFederationAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }

        public ActionResult SignInCallback()
        {
            using (AspNetUsersBLL user = new AspNetUsersBLL(UserIdentity.GetUserId()))
            {
                if (user.UpdateInfo(UserIdentity.GetUserName(), UserIdentity.GetUserEmail()) == AspNetUsersBLL.UserMessage.UserAdded)
                {
                    string url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/Users/Manage/";
                    using (TicketsBLL tickets = new TicketsBLL())
                    {
                        JobStorage.Current = new SqlServerStorage(
                            "SAIMHangFire",
                            new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });
                        BackgroundJob.Enqueue(() => UserLoginEmail.NotifyUserLogin(UserIdentity.GetUserName(), UserIdentity.GetUserId(), url, tickets.GetAdminsEmails("TIC")));
                    }
                }
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult SignOutCallback()
        {
            return RedirectToAction("Index", "Home");
        }
    }
}